package com.study.netty.websocket;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.time.LocalDateTime;

/**
 * TextWebSocketFrame: 在netty中,用于websocket专门处理文本的对象,frame时消息的载体
 */
public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {//TextWebSocketFrame在netty中是用于专门处理文本的对象,frame是消息的载体c

    //用于记录和管理所有客户端的channel
    private static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    private static int count = 0;

    protected void channelRead0(ChannelHandlerContext context, TextWebSocketFrame msg) throws Exception {
        //获取客户端传输过来的消息
        String text = msg.text();
        System.out.println("接收到的数据: \n" + text);

        for (Channel channel : clients) {
            channel.writeAndFlush(new TextWebSocketFrame("[服务器于]:" + LocalDateTime.now() + " 接收到消息,内容为:" + text));
        }
        //也可以用下面的方法,和上面的for循环效果相同
        //clients.writeAndFlush(new TextWebSocketFrame("[服务器接收到消息]" + LocalDateTime.now() + " :\n" + context));

    }

    /**
     * 当客户端链接服务端后,获取客户端的channel,并放到ChannelGroup去进行管理
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        clients.add(channel);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        //当触发handlerRemoved,ChannelGroup会自动移除对应客户端的channel
        //clients.remove(ctx.channel());
        System.out.println(">>>" + ++count);
        System.out.println("客户端断开,其短id为");
        System.out.println(ctx.channel().id().asShortText());
        System.out.println("客户端断开,其长id为");
        System.out.println(ctx.channel().id().asLongText());
    }


}
